package com.yanqu.road.server.gameplayer.module.activity.harps;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.activity.harps.*;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogHarpsActivityDraw;
import com.yanqu.road.entity.log.LogWitchDrawActivityDraw;
import com.yanqu.road.logic.bussiness.activity.HarpsBusiness;
import com.yanqu.road.pb.activity.harps.Harps;
import com.yanqu.road.server.cmd.player.DebugHelper;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.harps.confirm.HarpsPlayOneConfirm;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.harps.HarpsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class HarpsModule extends GeneralModule {
    public HarpsModule(GamePlayer player) {
        super(player);
    }

    private HarpsUserData userData;

    // 玩家已选奖励聚合 <奖励id， 奖励信息> 缓存
    private Map<Integer, HarpsRewardInfo> chooseRewardMap = new ConcurrentHashMap<>();

    // 按层分奖池 <层数， <奖励id， 奖励信息>> 缓存
    private Map<Integer, Map<Integer, HarpsRewardInfo>> floorMap = new ConcurrentHashMap<>();

    // 固定奖励聚合 <奖励id， 奖励信息>
    private Map<Integer, HarpsRewardInfo> fixRewardMap = new ConcurrentHashMap<>();

    // 自选奖池聚合 <奖励id， <奖励no， 奖励信息>>
    private Map<Integer, Map<Integer, HarpsRewardInfo>> remainChooseRewardMap = new ConcurrentHashMap<>();

    @Override
    public boolean loadData() {
        if (inShowTime()) {
            HarpsConfigSync config = HarpsMgr.getConfig();
            userData = HarpsBusiness.getHarpsUserData(config.getActivityId(), getUserId());
            if (userData == null) {
                initUserData();
            }
            initUserRewardInfo(HarpsBusiness.getHarpsRewardInfo(config.getActivityId(), getUserId()));
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                HarpsBusiness.addHarpsUserData(userData);
            } else if (userData.isUpdateOption()) {
                HarpsBusiness.updateHarpsUserData(userData);
            }
        }

        for (HarpsRewardInfo info : fixRewardMap.values()) {
            saveRewardInfo(info);
        }

        for (Map<Integer, HarpsRewardInfo> dataMap : remainChooseRewardMap.values()) {
            if (dataMap == null) {
                continue;
            }
            for (HarpsRewardInfo data : dataMap.values()) {
                saveRewardInfo(data);
            }
        }

        return true;
    }

    @Override
    public void afterLogin() {
        activityLogin();
    }

    /**
     * 刷新活动 || 登录
     */
    public void activityLogin() {
        initUserData();
        initUserRewardInfo(null);
        syncConfig();
        syncUserData();
    }

    /*
     * 初始化系统（系统解锁调用）
     */
    public void initSystem() {
        activityLogin();
    }

    /*
     * 高山鸣琴调试指令
     */
    public String harpsDebug(List<Integer> list) {
        if (!inShowTime()) {
            return "【活动通用指令】高山鸣琴：没活动";
        }
        if (list == null || list.isEmpty()) {
            return "【活动通用指令】高山鸣琴：指令参数不足";
        }
        switch (list.get(0)) {
            case 1:
                enterActivityCmd();
                return "【活动通用指令】高山鸣琴：进入活动";
            case 2:
                Harps.HarpsSetRewardInfo.Builder builder = Harps.HarpsSetRewardInfo.newBuilder();
                builder.setSeat(1);
                builder.setIndex(1);
                Harps.HarpsSetRewardInfo.Builder builder2 = Harps.HarpsSetRewardInfo.newBuilder();
                builder2.setSeat(2);
                builder2.setIndex(1);
                Harps.HarpsSetRewardInfo.Builder builder3 = Harps.HarpsSetRewardInfo.newBuilder();
                builder3.setSeat(3);
                builder3.setIndex(1);
                List<Harps.HarpsSetRewardInfo> req = new ArrayList<>();
                req.add(builder.build());
                req.add(builder2.build());
                req.add(builder3.build());
                setChooseRewardCmd(req);
                return "【活动通用指令】高山鸣琴：设置自选";
            case 3:
                player.getModule(HarpsModule.class).playCmd(false);
                return "【活动通用指令】高山鸣琴：单抽";
            case 4:
                player.getModule(HarpsModule.class).playCmd(true);
                return "【活动通用指令】高山鸣琴：十连";
            case 5:
                player.getModule(HarpsModule.class).resetChooseReward();
                return "【活动通用指令】高山鸣琴：重置奖励";
            case 6:
                playSimulate();
                return "【活动通用指令】高山鸣琴：模拟抽奖";
            default:
                return "【活动通用指令】高山鸣琴：指令参数 1 错误";
        }
    }

    /*
     * 进入活动
     */
    public int enterActivityCmd() {
        if (!inShowTime()) {
            return GameErrorCode.E_HARPS_ACTIVITY_NOT_FOUND;
        }
        Harps.HarpsEnterActivityResp.Builder builder = Harps.HarpsEnterActivityResp.newBuilder();
        builder.setRet(0);
        builder.setPlayerActivityInfo(parsePlayerInfo());
        player.sendPacket(ClientProtocol.U_HARPS_ENTER, builder);
        return builder.getRet();
    }

    /*
     * 获取剩余自选奖励
     */
    public int GetRemainRewardInfoCmd(int seat) {
        if (!inShowTime()) {
            return GameErrorCode.E_HARPS_ACTIVITY_NOT_FOUND;
        }
        if (seat <= 0 || seat > 3) {
            return GameErrorCode.E_HARPS_PARAM_ERROR;
        }
        Harps.HarpsRemainRewardInfoResp.Builder builder = Harps.HarpsRemainRewardInfoResp.newBuilder();
        for (Map<Integer, HarpsRewardInfo> rewardInfoMap : remainChooseRewardMap.values()) {
            for (HarpsRewardInfo rewardInfo : rewardInfoMap.values()) {
                if (rewardInfo.getSeat() != seat) {
                    continue;
                }
                Harps.HarpsRemainChooseRewardInfo.Builder builderReward = Harps.HarpsRemainChooseRewardInfo.newBuilder();
                builderReward.setSeat(seat);
                builderReward.setIndex(rewardInfo.getNo());
                builderReward.setRemainChooseNum((int) rewardInfo.getRemainChooseNum());
                builderReward.setRemainUnlockNum((int) rewardInfo.getRemainUnlockNum());
                builder.addRemainRewardInfo(builderReward);
            }
        }
        builder.setRet(0);
        player.sendPacket(ClientProtocol.U_HARPS_REMAIN_REWARD, builder);
        return builder.getRet();
    }

    /*
     * 设置自选奖励
     */
    public int setChooseRewardCmd(List<Harps.HarpsSetRewardInfo> rewardInfos) {
        if (!inShowTime()) {
            return GameErrorCode.E_HARPS_ACTIVITY_NOT_FOUND;
        }
        if (rewardInfos == null || rewardInfos.isEmpty()) {
            return GameErrorCode.E_HARPS_PARAM_ERROR;
        }

        List<HarpsRewardInfo> harpsRewardInfos = new ArrayList<>();
        HarpsConfigSync config = HarpsMgr.getConfig();
        for (Harps.HarpsSetRewardInfo info : rewardInfos) {
            int seat = info.getSeat();
            int no = info.getIndex();
            if (seat <= 0 || seat > 3 || no <= 0) {
                return GameErrorCode.E_HARPS_PARAM_ERROR;
            }
            if (!chooseRewardMap.isEmpty()) {
                boolean isHas = false;
                for (HarpsRewardInfo rewardInfo : chooseRewardMap.values()) {
                    if (rewardInfo.getSeat() == seat) {
                        isHas = true;
                        break;
                    }
                }
                if (isHas) {
                    return GameErrorCode.E_HARPS_SETED_REWARD_SEAT;
                }
            }
            HarpsRewardInfo harpsRewardInfo = null;
            for (Map<Integer, HarpsRewardInfo> rewardInfoMap : remainChooseRewardMap.values()) {
                harpsRewardInfo = rewardInfoMap.get(no);
                if (harpsRewardInfo == null) {
                    continue;
                }
                if (harpsRewardInfo.getSeat() != seat) {
                    continue;
                }
                break;
            }
            if (harpsRewardInfo == null) {
                return GameErrorCode.E_HARPS_NO_REWARD_INDEX;
            }
            if (harpsRewardInfo.getRemainUnlockNum() > config.getChooseFloorNoUnlockNum()) {
                return GameErrorCode.E_HARPS_REWARD_NO_UNLOCK;
            }
            if (harpsRewardInfo.getRemainChooseNum() != config.getRemainChooseNumNoLimit() && harpsRewardInfo.getRemainChooseNum() <= 0) {
                return GameErrorCode.E_HARPS_REWARD_NO_CHOOSE_NUM;
            }
            harpsRewardInfos.add(harpsRewardInfo);
        }

        // 修改数据
        for (HarpsRewardInfo harpsRewardInfo : harpsRewardInfos) {
            harpsRewardInfo.setIsCurChoose(true);
            //harpsRewardInfo.setRemainChooseNum(harpsRewardInfo.getRemainChooseNum() == config.getRemainChooseNumNoLimit() ? harpsRewardInfo.getRemainChooseNum() : harpsRewardInfo.getRemainChooseNum() - 1);
            chooseRewardMap.put(harpsRewardInfo.getId(), harpsRewardInfo);
        }

        Harps.HarpsSetRewardResp.Builder builder = Harps.HarpsSetRewardResp.newBuilder();
        for (Harps.HarpsRemainChooseRewardInfo.Builder builderReward : parsePlayerRemainChooseInfo()) {
            builder.addRemainChoose(builderReward);
        }
        builder.setPlayer(parsePlayerInfo());
        builder.setRet(0);
        player.sendPacket(ClientProtocol.U_HARPS_SET_REWARD, builder);
        return builder.getRet();
    }

    /*
     * 重置奖励
     */
    public int resetChooseReward() {
        if (!inShowTime()) {
            return GameErrorCode.E_HARPS_ACTIVITY_NOT_FOUND;
        }

        if (chooseRewardMap.isEmpty()) {
            return GameErrorCode.E_HARPS_CHOOSE_REWARD_NULL;
        }

        for (HarpsRewardInfo rewardInfo : chooseRewardMap.values()) {
            rewardInfo.setIsCurChoose(false);
            rewardInfo.setIsGetReward(false);
        }
        chooseRewardMap.clear();

        //HarpsConfigSync config = HarpsMgr.getConfig();
        //userData.setRound(1);
        //userData.setPerDrawReduceCount(config.getParamConfig().getMountainDrawNumByRound(userData.getRound()));
        //userData.setFloor(1);
        resetFixRewardColor();

        Harps.HarpsResetResp.Builder builder = Harps.HarpsResetResp.newBuilder();
        for (Harps.HarpsRemainChooseRewardInfo.Builder builderReward : parsePlayerRemainChooseInfo()) {
            builder.addRemainChoose(builderReward);
        }
        builder.setPlayer(parsePlayerInfo());
        builder.setRet(0);
        player.sendPacket(ClientProtocol.U_HARPS_RESET, builder);
        return builder.getRet();
    }

    /*
     * 演奏 - 抽奖
     */
    public int playCmd(boolean isTenDraws) {
        if (!inShowTime()) {
            return GameErrorCode.E_HARPS_ACTIVITY_NOT_FOUND;
        }

        if (chooseRewardMap.isEmpty()) {
            return GameErrorCode.E_HARPS_CHOOSE_REWARD_NULL;
        }

        long getScore = 0;
        long tempScore = userData.getScore();
        String rewardForLog = "";
        boolean isBig = false;
        int playNumCur = 1;
        boolean needSaveLog = false;
        if (isTenDraws) {
            // 十连
            Harps.HarpsPlayResp.Builder builder = Harps.HarpsPlayResp.newBuilder();
            StringBuilder reward = new StringBuilder();
            for (int i = 0; i < 10; i++) {
                HarpsPlayOneConfirm confirm = new HarpsPlayOneConfirm(userData, player, floorMap);
                confirm.setTen(true);
                confirm.exec();
                Harps.HarpsPlayResp.Builder confirmBuilder = confirm.getBuilder();
                if (confirmBuilder.getRet() != 0) {
                    builder.setRet(i == 0 ? confirmBuilder.getRet() : 0);
                    break;
                }
                builder.setRet(0);
                builder.addRewardInfo(confirmBuilder.getRewardInfo(0));
                reward.append(confirmBuilder.getReward()).append(";");
                if (confirm.isBigReward()) {
                    isBig = true;
                    break;
                }
            }
            builder.setScore((int) (userData.getScore() - tempScore));
            builder.setPlayer(parsePlayerInfo());
            builder.setReward(reward.toString());
            player.sendPacket(ClientProtocol.U_HARPS_PLAY, builder);

            // 日志
            getScore = userData.getScore() - tempScore;
            rewardForLog = reward.toString();
            playNumCur = builder.getRewardInfoCount();
            needSaveLog = builder.getRet() == 0;
        } else {
            // 单抽
            HarpsPlayOneConfirm confirm = new HarpsPlayOneConfirm(userData, player, floorMap);
            confirm.exec();

            // 日志
            getScore = userData.getScore() - tempScore;
            rewardForLog = confirm.getBuilder().getReward();
            isBig = confirm.isBigReward();
            needSaveLog = confirm.getBuilder().getRet() == 0;
        }
        if (needSaveLog) {
            HarpsConfigSync config = HarpsMgr.getConfig();
            LogHarpsActivityDraw log = new LogHarpsActivityDraw(config.getActivityId(), getUserId(), userData.getPlayNum(), playNumCur, getScore,
                    userData.getScore(), rewardForLog, isBig, System.currentTimeMillis());
            AutoLogMgr.add(log);
        }
        return 0;
    }

    /*
     * 抽奖单次
     */
    private int playOne() {
        if (userData == null) {
            initUserData();
        }

        HarpsConfigSync config = HarpsMgr.getConfig();
        int mountainItemId = config.getParamConfig().getMountainItemId();
        Property property = new Property(mountainItemId, userData.getPerDrawReduceCount());
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(property)) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }

        // 随机颜色
        List<List<Integer>> mountainFloorPro = config.getParamConfig().getMountainFloorPro();
        List<Integer> list = mountainFloorPro.get(userData.getFloor() - 1);
        if (list == null || list.isEmpty() || list.get(0) != userData.getFloor()) {
            return GameErrorCode.E_HARPS_CONFIG_ERROR;
        }
        list.remove(0);
        int index = HarpsMgr.getRandomHelper().getSafeRandomIndexByWeight(list);
        eHarpsColorEnum color = eHarpsColorEnum.forValue(index);
        if (index < eHarpsColorEnum.Color_TouMing.getValue() || index > eHarpsColorEnum.Color_Pink.getValue() || color == null) {
            return GameErrorCode.E_HARPS_RANDOM_ERROR;
        }

        int floor = userData.getFloor();
        if (userData.getPlayNum() >= config.getParamConfig().getMountainMaxDraw()) {
            // 如果演奏次数达到对应的保底，则只会上升
            color = eHarpsColorEnum.Color_Gold;
        }
        if (color.getValue() == eHarpsColorEnum.Color_Gold.getValue()) {
            floor = floor + 1;
        }else if (color.getValue() == eHarpsColorEnum.Color_Pink.getValue()) {
            floor = floor - 1;
        }

        Harps.HarpsPlayResp.Builder builder = Harps.HarpsPlayResp.newBuilder();
        if (floor == config.getHighestFloor()) {
            // 抽到大奖了
            List<Integer> weightList = new ArrayList<>();
            List<HarpsRewardInfo> rewardInfos = new ArrayList<>();
            for (HarpsRewardInfo rewardInfo : chooseRewardMap.values()) {
                HarpsMountConfig mountConfig = config.getMountConfigMap().get(rewardInfo.getId());
                weightList.add(mountConfig.getWeight());
                rewardInfos.add(rewardInfo);
            }
            int indexReward = HarpsMgr.getRandomHelper().getSafeRandomIndexByWeight(weightList);
            HarpsRewardInfo harpsRewardInfo = rewardInfos.get(indexReward);
            if (harpsRewardInfo == null) {
                return GameErrorCode.E_HARPS_RANDOM_ERROR;
            }

            // 扣道具
            if (!player.getModule(CurrencyModule.class).removeCurrency(property, eLogMoneyType.Harps, eLogMoneyType.HarpsPlay)) {
                return GameErrorCode.E_HARPS_USE_ITEM_ERROR;
            }

            // 给奖励
            HarpsMountConfig mountConfig = config.getMountConfigMap().get(harpsRewardInfo.getId());
            if (mountConfig == null) {
                return GameErrorCode.E_HARPS_NO_REWARD_CONFIG;
            }
            userData.setScore(userData.getScore() + config.getParamConfig().getMountainScoreGain() * userData.getPerDrawReduceCount());
            userData.setScoreUpdateTime(System.currentTimeMillis());
            userData.setPlayNum(1);
            String reward = config.getHighestReward(harpsRewardInfo.getId(), harpsRewardInfo.getNo());
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Harps, eLogMoneyType.HarpsPlayReward);
            builder.setRet(0);
            builder.setPlayer(parsePlayerInfo());
            Harps.HarpsGainRewardInfo.Builder builderReward = Harps.HarpsGainRewardInfo.newBuilder();
            builderReward.setFloor(floor);
            builderReward.setSeat(harpsRewardInfo.getSeat());
            builder.addRewardInfo(builderReward);
            builder.setReward(reward);
        } else {
            // 普通奖励
            List<Integer> weightList = new ArrayList<>();
            List<HarpsRewardInfo> rewardInfos = new ArrayList<>();
            for (HarpsRewardInfo rewardInfo : fixRewardMap.values()) {
                HarpsMountConfig mountConfig = config.getMountConfigMap().get(rewardInfo.getId());
                weightList.add(mountConfig.getWeight());
                rewardInfos.add(rewardInfo);
            }
            int indexReward = HarpsMgr.getRandomHelper().getSafeRandomIndexByWeight(weightList);
            HarpsRewardInfo harpsRewardInfo = rewardInfos.get(indexReward);
            if (harpsRewardInfo == null) {
                return GameErrorCode.E_HARPS_RANDOM_ERROR;
            }

            // 扣道具
            if (!player.getModule(CurrencyModule.class).removeCurrency(property, eLogMoneyType.Harps, eLogMoneyType.HarpsPlay)) {
                return GameErrorCode.E_HARPS_USE_ITEM_ERROR;
            }

            // 给奖励
            HarpsMountConfig mountConfig = config.getMountConfigMap().get(harpsRewardInfo.getId());
            if (mountConfig == null) {
                return GameErrorCode.E_HARPS_NO_REWARD_CONFIG;
            }
            userData.setScore(userData.getScore() + config.getParamConfig().getMountainScoreGain() * userData.getPerDrawReduceCount());
            userData.setScoreUpdateTime(System.currentTimeMillis());
            userData.setPlayNum(userData.getPlayNum() + 1);
            String reward = config.getMountConfigMap().get(harpsRewardInfo.getId()).getAward();
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Harps, eLogMoneyType.HarpsPlayReward);
            builder.setRet(0);
            builder.setPlayer(parsePlayerInfo());
            Harps.HarpsGainRewardInfo.Builder builderReward = Harps.HarpsGainRewardInfo.newBuilder();
            builderReward.setFloor(floor);
            builderReward.setSeat(harpsRewardInfo.getSeat());
            builder.addRewardInfo(builderReward);
            builder.setReward(reward);
        }
        player.sendPacket(ClientProtocol.U_HARPS_PLAY, builder);
        return 0;
    }

    /*
     * 抽奖10次
     */
    private int playSimulate() {
        Map<String, Integer> tj = new ConcurrentHashMap<>();
        List<Integer> list = new ArrayList<>();
        list.add(2);
        for (int i = 0; i < 10000; i++) {
            HarpsPlayOneConfirm confirm = new HarpsPlayOneConfirm(userData, player, floorMap);
            confirm.exec();
            if (confirm.getBuilder().getRet() == 10206) {
                harpsDebug(list);
                continue;
            }
            if (confirm.getBuilder().getRet() != 0) {
                break;
            }
            Harps.HarpsGainRewardInfo rewardInfo = confirm.getBuilder().getRewardInfo(0);
            int temp = tj.computeIfAbsent(rewardInfo.getFloor() + "_" + rewardInfo.getSeat(), K -> 0);
            tj.put(rewardInfo.getFloor() + "_" + rewardInfo.getSeat(), temp + 1);
        }

        System.out.println("======== 模拟 10000 次抽奖 ========");
        for (Map.Entry<String, Integer> entry : tj.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        return 0;
    }

    /*
     * 协议 - 返回玩家剩余奖励
     */
    private List<Harps.HarpsRemainChooseRewardInfo.Builder> parsePlayerRemainChooseInfo() {
        List<Harps.HarpsRemainChooseRewardInfo.Builder> ret = new ArrayList<>();
        for (Map<Integer, HarpsRewardInfo> rewardInfoMap : remainChooseRewardMap.values()) {
            for (HarpsRewardInfo rewardInfo : rewardInfoMap.values()) {
                Harps.HarpsRemainChooseRewardInfo.Builder builderReward = Harps.HarpsRemainChooseRewardInfo.newBuilder();
                builderReward.setSeat(rewardInfo.getSeat());
                builderReward.setIndex(rewardInfo.getNo());
                builderReward.setRemainChooseNum((int) rewardInfo.getRemainChooseNum());
                builderReward.setRemainUnlockNum((int) rewardInfo.getRemainUnlockNum());
                ret.add(builderReward);
            }
        }
        return ret;
    }

    /*
     * 协议 - 返回玩家信息
     */
    public Harps.HarpsPlayerActivityInfo.Builder parsePlayerInfo() {
        Harps.HarpsPlayerActivityInfo.Builder builderPlayer = Harps.HarpsPlayerActivityInfo.newBuilder();
        builderPlayer.setCurrentFloor(userData.getFloor());
        builderPlayer.setPerDrawReduceCount(userData.getPerDrawReduceCount());
        builderPlayer.setScore(userData.getScore());
        builderPlayer.setPlayNum(userData.getPlayNum());
        for (HarpsRewardInfo rewardInfo : fixRewardMap.values()) {
            Harps.HarpsRewardInfo.Builder builder = Harps.HarpsRewardInfo.newBuilder();
            builder.setFloor(rewardInfo.getFloor());
            builder.setSeat(rewardInfo.getSeat());
            builder.setColor(rewardInfo.getColor());
            builderPlayer.addFloor(builder);
        }
        for (Map<Integer, HarpsRewardInfo> rewardInfoMap : remainChooseRewardMap.values()) {
            for (HarpsRewardInfo rewardInfo : rewardInfoMap.values()) {
                if (rewardInfo.getIsCurChoose()) {
                    Harps.HarpsChooseRewardInfo.Builder builder = Harps.HarpsChooseRewardInfo.newBuilder();
                    builder.setSeat(rewardInfo.getSeat());
                    builder.setIndex(rewardInfo.getNo());
                    builder.setIsGetReward(rewardInfo.getIsGetReward());
                    builderPlayer.addChoose(builder);
                }
            }
        }
        return builderPlayer;
    }


    /**
     * 初始化玩家数据
     */
    private synchronized void initUserData() {
        if (inShowTime()) {
            HarpsConfigSync config = HarpsMgr.getConfig();
            if (userData == null || config.getActivityInfo().getActivityId() != userData.getActivityId()) {
                HarpsUserData tempUserData = new HarpsUserData();
                tempUserData.setActivityId(config.getActivityId());
                tempUserData.setUserId(getUserId());
                tempUserData.setRound(1);
                tempUserData.setPerDrawReduceCount(config.getParamConfig().getMountainDrawNumByRound(tempUserData.getRound()));
                tempUserData.setInsertOption();
                userData = tempUserData;
            }
            userData.setFloor(/*userData.getFloor() == config.getHighestFloor()|| */userData.getFloor() == 0 ? 1 : userData.getFloor());
            if (userData.getScore() > 0) {
                player.notifyListener(eGamePlayerEventType.HarpsScoreRank.getValue(), (long)userData.getScore());
            }
        }
    }

    /*
     * 初始化玩家奖励信息
     */
    private synchronized void initUserRewardInfo(Map<Integer, Map<Integer, HarpsRewardInfo>> rewardMap) {
        if (inShowTime()) {
            HarpsConfigSync config = HarpsMgr.getConfig();
            if (fixRewardMap.isEmpty() || fixRewardMap.get(1).getActivityId() != config.getActivityId()) {
                if (rewardMap == null) {
                    rewardMap = new ConcurrentHashMap<>();
                    // 初始化角色固定奖励部分
                    for (List<Integer> integers : config.getParamConfig().getMountainColorNum()) {
                        if (integers == null || integers.isEmpty()) {
                            continue;
                        }
                        int floor = integers.get(0);
                        int color1 = integers.get(1); // 透明气泡数量
                        int color2 = integers.get(2); // 金色气泡数量
                        int color3 = integers.get(3); // 粉色气泡数量
                        List<HarpsMountConfig> floorList = config.getMountConfigByFloor(floor);
                        if (color1 + color2 + color3 != floorList.size()) {
                            continue;
                        }
                        List<eHarpsColorEnum> initPaoColor = getInitPaoColor(color1, color2, color3);
                        if (initPaoColor.size() != floorList.size()) {
                            continue;
                        }
                        Collections.shuffle(floorList);
                        for (int i = 0; i < floorList.size(); i++) {
                            HarpsMountConfig harpsMountConfig = floorList.get(i);
                            HarpsRewardInfo harpsRewardInfo = new HarpsRewardInfo();
                            harpsRewardInfo.setActivityId(config.getActivityId());
                            harpsRewardInfo.setUserId(getUserId());
                            harpsRewardInfo.setId(harpsMountConfig.getPrizeId());
                            harpsRewardInfo.setNo(0);   // 固定奖励部分的 no 固定为 0，自选层才有值，且从 1 开始
                            harpsRewardInfo.setFloor(harpsMountConfig.getFloor());
                            harpsRewardInfo.setSeat(harpsMountConfig.getSeat());
                            harpsRewardInfo.setColor(initPaoColor.get(i).getValue());
                            harpsRewardInfo.setRemainChooseNum(config.getRemainChooseNumNoLimit()); // -1 表示无上限
                            harpsRewardInfo.setRemainUnlockNum(config.getChooseFloorNoUnlockNum()); // 0 表示无解锁次数限制
                            harpsRewardInfo.setIsGetReward(false);
                            harpsRewardInfo.setIsCurChoose(false);
                            harpsRewardInfo.setInsertOption();
                            Map<Integer, HarpsRewardInfo> harpsRewardInfos = rewardMap.computeIfAbsent(harpsRewardInfo.getId(), k -> new ConcurrentHashMap<>());
                            harpsRewardInfos.put(harpsRewardInfo.getNo(), harpsRewardInfo);
                        }
                    }

                    // 初始化角色自选奖励部分
                    for (HarpsMountConfig harpsMountConfig : config.getMountConfigByFloor(config.getHighestFloor())) {
                        List<String> strings = StringUtils.stringToStringList(harpsMountConfig.getAward(), "\\|");
                        if (strings.isEmpty()) {
                            continue;
                        }
                        for (String string : strings) {
                            List<String> strs = StringUtils.stringToStringList(string, "#");
                            if (strs.isEmpty()) {
                                continue;
                            }
                            List<String> strRewards = StringUtils.stringToStringList(strs.get(1), ",");
                            if (strRewards.isEmpty()) {
                                continue;
                            }
                            HarpsRewardInfo harpsRewardInfo = new HarpsRewardInfo();
                            harpsRewardInfo.setActivityId(config.getActivityId());
                            harpsRewardInfo.setUserId(getUserId());
                            harpsRewardInfo.setId(harpsMountConfig.getPrizeId());
                            harpsRewardInfo.setNo(StringUtils.parseInt(strs.get(0)));   // 固定奖励部分的 no 固定为 0，自选层才有值，且从 1 开始
                            harpsRewardInfo.setFloor(harpsMountConfig.getFloor());
                            harpsRewardInfo.setSeat(harpsMountConfig.getSeat());
                            harpsRewardInfo.setColor(eHarpsColorEnum.Color_Reset.getValue());
                            harpsRewardInfo.setRemainChooseNum(Long.parseLong(strRewards.get(1))); // -1 表示无上限
                            harpsRewardInfo.setRemainUnlockNum(Long.parseLong(strRewards.get(2))); // 0 表示无解锁次数限制
                            harpsRewardInfo.setIsGetReward(false);
                            harpsRewardInfo.setIsCurChoose(false);
                            harpsRewardInfo.setInsertOption();
                            Map<Integer, HarpsRewardInfo> harpsRewardInfos = rewardMap.computeIfAbsent(harpsRewardInfo.getId(), k -> new ConcurrentHashMap<>());
                            harpsRewardInfos.put(harpsRewardInfo.getNo(), harpsRewardInfo);
                        }
                    }
                }
                if (rewardMap.isEmpty()) {
                    return;
                }

                // 先清除旧的
                chooseRewardMap.clear();
                floorMap.clear();
                fixRewardMap.clear();
                remainChooseRewardMap.clear();

                // 增加新的
                floorMap.put(config.getHighestFloor(), chooseRewardMap);
                for (Map<Integer, HarpsRewardInfo> rewardInfoMap : rewardMap.values()) {
                    for (HarpsRewardInfo rewardInfo : rewardInfoMap.values()) {
                        if (rewardInfo.getFloor() == config.getHighestFloor()) {
                            Map<Integer, HarpsRewardInfo> harpsRewardInfos = remainChooseRewardMap.computeIfAbsent(rewardInfo.getId(), k -> new ConcurrentHashMap<>());
                            harpsRewardInfos.put(rewardInfo.getNo(), rewardInfo);
                            if (rewardInfo.getIsCurChoose()) {
                                chooseRewardMap.put(rewardInfo.getId(), rewardInfo);
                            }
                        } else {
                            fixRewardMap.put(rewardInfo.getId(), rewardInfo);
                            Map<Integer, HarpsRewardInfo> floorRewardMap = floorMap.computeIfAbsent(rewardInfo.getFloor(), k -> new ConcurrentHashMap<>());
                            floorRewardMap.put(rewardInfo.getId(), rewardInfo);
                        }
                    }
                }
            }
            log.debug("自选层奖池：{}", JSON.toJSONString(remainChooseRewardMap));
            log.debug("固定层奖池：{}", JSON.toJSONString(fixRewardMap));
        }
    }

    /*
     * 获取初始化气泡颜色
     */
    private List<eHarpsColorEnum> getInitPaoColor(int tm, int gold, int pink) {
        List<eHarpsColorEnum> ret = new ArrayList<>();
        for (int i = 0; i < tm; i++) {
            ret.add(eHarpsColorEnum.Color_TouMing);
        }
        for (int i = 0; i < gold; i++) {
            ret.add(eHarpsColorEnum.Color_Gold);
        }
        for (int i = 0; i < pink; i++) {
            ret.add(eHarpsColorEnum.Color_Pink);
        }
        return ret;
    }

    /*
     * 重置固定奖励颜色位置
     */
    private void resetFixRewardColor() {
        if (!inShowTime() || fixRewardMap.isEmpty()) {
            return;
        }
        HarpsConfigSync config = HarpsMgr.getConfig();
        // 重新初始化角色固定奖励颜色位置
        for (List<Integer> integers : config.getParamConfig().getMountainColorNum()) {
            if (integers == null || integers.isEmpty()) {
                continue;
            }
            int floor = integers.get(0);
            int color1 = integers.get(1); // 透明气泡数量
            int color2 = integers.get(2); // 金色气泡数量
            int color3 = integers.get(3); // 粉色气泡数量
            List<HarpsMountConfig> floorList = config.getMountConfigByFloor(floor);
            if (color1 + color2 + color3 != floorList.size()) {
                continue;
            }
            List<eHarpsColorEnum> initPaoColor = getInitPaoColor(color1, color2, color3);
            if (initPaoColor.size() != floorList.size()) {
                continue;
            }
            Collections.shuffle(floorList);
            for (int i = 0; i < floorList.size(); i++) {
                HarpsMountConfig harpsMountConfig = floorList.get(i);
                HarpsRewardInfo harpsRewardInfo = fixRewardMap.get(harpsMountConfig.getPrizeId());
                harpsRewardInfo.setColor(initPaoColor.get(i).getValue());
            }
        }
    }

    /*
     * inShowTime
     */
    private boolean inShowTime() {
        HarpsConfigSync config = HarpsMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo()) || !SystemOpenMgr.checkSystemOpen(player.getUserId(), eSystemId.Harps.getValue())) {
            return false;
        }
        return true;
    }

    /*
     * inActivityTime 10 - 22
     */
    public boolean inActivityTime() {
        HarpsConfigSync config = HarpsMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo()) || !SystemOpenMgr.checkSystemOpen(player.getUserId(), eSystemId.Harps.getValue())) {
            return false;
        }
        long start = DateHelper.getZeroTimeStamp(config.getActivityInfo().getBeginTime()) + 10 * DateHelper.SECOND_MILLIONS;
        if (System.currentTimeMillis() < start) {
            return false;
        }
        if (!ActivityMgr.activityInTime(config.getActivityInfo())) {
            return false;
        }
        return true;
    }

    /**
     * 同步配置
     */
    public void syncConfig() {
        if (inShowTime()) {
            HarpsConfigSync config = HarpsMgr.getConfig();
            Harps.HarpsConfigSync.Builder builder = Harps.HarpsConfigSync.newBuilder();
            for (HarpsMountConfig mountConfig : config.getMountConfigMap().values()) {
                Harps.HarpsMountConfig.Builder builderMount = Harps.HarpsMountConfig.newBuilder();
                builderMount.setPrizeId(mountConfig.getPrizeId());
                builderMount.setFloor(mountConfig.getFloor());
                builderMount.setIsOptional(mountConfig.getIsOptional());
                builderMount.setSeat(mountConfig.getSeat());
                builderMount.setAward(mountConfig.getAward());
                builderMount.setWeight(mountConfig.getWeight());
                builder.addMount(builderMount);
            }
            player.sendPacket(ClientProtocol.U_HARPS_SYNC_CONFIG, builder);
        }
    }

    /*
     * 同步用户数据
     */
    public void syncUserData() {
        // 进入活动再进行同步
    }

    /*
     * 保存奖励信息
     */
    private void saveRewardInfo(HarpsRewardInfo data) {
        if (data != null) {
            if (data.isInsertOption()) {
                HarpsBusiness.addHarpsRewardInfo(data);
            } else if (data.isUpdateOption()) {
                HarpsBusiness.updateHarpsRewardInfo(data);
            }
        }
    }

    /*
     * 增加解锁次数
     */
    public void tryAddUnlockNum(int seat) {
        if (!inShowTime()) {
            return;
        }
        for (Map<Integer, HarpsRewardInfo> rewardInfoMap : remainChooseRewardMap.values()) {
            if (rewardInfoMap == null) {
                continue;
            }
            for (HarpsRewardInfo rewardInfo : rewardInfoMap.values()) {
                if (rewardInfo.getSeat() == seat && rewardInfo.getRemainUnlockNum() > 0) {
                    rewardInfo.setRemainUnlockNum(rewardInfo.getRemainUnlockNum() - 1);
                }
            }
        }
    }
}
